package com.cxm.weilai.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.math.BigDecimal;
import java.util.Calendar;

public class ParamUtil {
    private static Log logger = LogFactory.getLog(ParamUtil.class);

    public static Object convertObject(String type, String paramValue) {
        if (StringUtils.isBlank(paramValue)) return null;
        ParamType paramType = ParamType.parseOf(type);
        return convertObject(paramType, paramValue, null);
    }

    public static Object convertObject(ParamType paramType, String paramValue, Object defaultValue) {
        if (StringUtils.isBlank(paramValue)) {
            if (null == defaultValue) return null;
            else return defaultValue;
        }
        Object value = null;
        try {
            switch (paramType) {
                case L:
                    value = new Long(paramValue);
                    break;
                case N:
                    value = new Integer(paramValue);
                    break;
                case BD:
                    value = new BigDecimal(paramValue);
                    break;
                case FT:
                    value = new Float(paramValue);
                    break;
                case DB:
                    value = new Double(paramValue);
                    break;
                case SN:
                    value = new Short(paramValue);
                    break;
                case D:
                    value = DateUtils.parseDate(paramValue, new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy" +
                            "-MM-dd HH:mm"});
                    break;
                case DL:
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(DateUtils.parseDate(paramValue, new String[]{"yyyy-MM-dd"}));
                    value = DateUtil.setStartDay(cal).getTime();
                    break;
                case DG:
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(DateUtils.parseDate(paramValue, new String[]{"yyyy-MM-dd"}));
                    value = DateUtil.setEndDay(calendar).getTime();
                    break;
                case S:
                default:
                    value = paramValue;
                    break;
            }
        } catch (Exception ex) {
            logger.error("the data value is not right for the query filed type:" + ex.getMessage());
        }
        return value;
    }

    public static Object convertObject(ParamType paramType, String paramValue) {
        return convertObject(paramType, paramValue, null);
    }

    public static String StrTrim(String string) {
        if (string != null) {
            string = string.trim();
        }
        return string;
    }
}
